import AuditmainAPI from '../../common/api/biosafety/auditmain.api.js';
import doT from '../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from '../../common/dictionary/dictionary-type.js';
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from '../../common/api/file-request.js';

(function (window, document, $) {
    const toolbarTemplate = `<div class="toolbar" id="me-date-screening">
<div class="toolbar-inner">
<span style='margin:0 auto;margin-top:10px'>请选择业务日期</span>
<a href="javascript:;" class="picker-button close-picker" style="color:#427ce7;font-size:20px;margin-right:18px;display:inline-block;line-height:100%">{{closeText}}</a>
</div>
</div>`;

    let personList = [],
        categoryInfo = [],
        typeInfo = [],
        farmTypeInfo = [],
        placeInfo = [],
        resultInfo = [],
        billStatusInfo = {},
        farmOrgInfo = [];

    const _json = Utils.ParsingUrl(window.location);
    const addsaleTemplate = doT.template($('#addsaleorders-template').text());
    const _page = {
        searchInfo: '',
        startDate: '',
        endDate: '',
        billStatus: 3,
        orgId: '',
        fitlerOrgs: [],
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    };

    let _vm,
        _ownOrgs = [],
        _stuffInfo = [],
        _pickerTime,
        _deliveryTime,
        savetype,
        uersInfo,
        getMainMessage = [],
        custom,
        saleOrgsinfo,
        getEntryInfo = [],
        operaEntry,
        operaEntryId,
        nextEntryId = 0,
        timer = null,
        addstyleEntry,
        edistyleEntry,
        renderEntryInfo = [],
        getMainInfo = [],
        entriesmater = {};
    let _levelType = [],
        _personOrg = [],
        _pigTypeList = [];

    $(async function () {
        _vm = new Vue({
            el: '#addsaleorders-form',
            data() {
                return {
                    category: 2, // 千点评分审查
                    farmOrg: {
                        id: '',
                        name: '',
                    },
                    type: '',
                    bizDate: moment(new Date()).format('YYYY-MM-DD'),
                    adress: '',
                    adressName: '',
                    scoreDate: '',
                    scorer: '',
                    scorerIds: '',
                    remark: '',
                    leaders: '',
                    leaderIds: '',
                    entires: [
                        {
                            isHave: false,
                            seq: '',
                            auditItemId: '',
                            text: '',
                            weight: '',
                            isQualified: false,
                            isRectify: false,
                            deduct: '',
                            reason: '',
                            suggestion: '',
                            principal: '',
                            principalIds: '',
                            timeLimit: '',
                            result: '',
                            image: '',
                            remark: '',
                        },
                    ],
                    uploadCount: 0,
                    images: [], ///处理weui自带上传插件回显重新上传时的问题
                    attaches: [],
                    page: { ..._page },
                };
            },
            methods: {
                submit() {
                    savedata();
                },
            },
        });
        await initSelectValue();
        ctlReturn();
        selfAdaption();
        _initCommand();
        _delSalesEntry();
        _ediSalesEntry();
        uploadInit();
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });

    // 初始化数据
    const _initCommand = async () => {
        // 编辑赋值
        if (Utils.IsNotNull(getUrlKey('id'))) {
            $('#informationSubmit').text('保存');
            $('title').text('审查表-编辑');
            AuditmainAPI.getAuditTablesDetail(getUrlKey('id')).then((res) => {
                const propertiesToCopy = ['category', 'farmOrg', 'type', 'bizDate', 'adress', 'adressName', 'scoreDate', 'scorer', 'scorerIds', 'remark', 'leaders', 'leaderIds'];
                propertiesToCopy.reduce((obj, prop) => {
                    _vm[prop] = res[prop];
                }, {});
                _vm.bizDate = res.bizFormObj.bizDate.split(' ')[0].replace(/\//g, '-');
                _vm.scoreDate = res.scoreDate.split(' ')[0].replace(/\//g, '-');
                _vm.farmOrg.id = res.farmOrg?.id || '';
                _vm.farmOrg.name = res.farmOrg?.name || '';

                $('#type').val(_vm.type).trigger('change');
                $('#adress').val(_vm.adress).trigger('change');
                $('#farmOrg').val(_vm.farmOrg?.id).trigger('change');
                let farmOrginfo = cutstr(_vm.farmOrg.name, 30); // 截取字符串
                $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').text(farmOrginfo);
                $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });

                if (_vm.scorerIds.includes(',')) {
                    let newlist = _vm.scorerIds.split(',');
                    $('#scorer').val(newlist).trigger('change');
                } else {
                    $('#scorer').val(_vm.scorerIds).trigger('change');
                }
                let scorerinfo = cutstr(_vm.scorer, 30); // 截取字符串
                $('#scorer').next('.select2-container').find('.select2-selection__rendered').text(scorerinfo);
                $('#scorer').next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });

                // 存储主表数据
                let datas = {
                    category: 2, // 千点
                    farmOrg: {
                        id: _vm.farmOrg?.id || '',
                        name: _vm.farmOrg?.name || '',
                    },
                    type: _vm.type,
                    bizDate: _vm.bizDate,
                    adress: _vm.adress,
                    adressName: _vm.adressName,
                    scoreDate: _vm.scoreDate,
                    scorer: _vm.scorer,
                    scorerIds: _vm.scorerIds,
                    remark: _vm.remark,
                    leaders: _vm.leaders,
                    leaderIds: _vm.leaderIds,
                };
                JSON.stringify(Utils.SetSessionStorage('getMainMessage', datas));

                // 存入SessionStorage
                JSON.stringify(Utils.SetSessionStorage('getEntryInfo', res.entries));
                _initEntry();
            });
        } else {
            // 获取主表数据
            getMainMessage = JSON.parse(Utils.GetSessionStorage('getMainMessage'));
            // 主表数据赋值
            if (Utils.IsNotNull(getMainMessage)) {
                const propertiesToCopy = ['category', 'farmOrg', 'type', 'bizDate', 'adress', 'adressName', 'scoreDate', 'scorer', 'scorerIds', 'remark', 'leaders', 'leaderIds'];
                propertiesToCopy.reduce((obj, prop) => {
                    _vm[prop] = getMainMessage[prop];
                }, {});
                _vm.bizDate = getMainMessage.bizDate.split(' ')[0].replace(/\//g, '-');
                _vm.scoreDate = getMainMessage.scoreDate.split(' ')[0].replace(/\//g, '-');
                _vm.farmOrg.id = getMainMessage.farmOrg?.id || '';
                _vm.farmOrg.name = getMainMessage.farmOrg?.name || '';

                $('#type').val(_vm.type).trigger('change');
                $('#adress').val(_vm.adress).trigger('change');
                $('#farmOrg').val(_vm.farmOrg?.id).trigger('change');
                let farmOrginfo = cutstr(_vm.farmOrg.name, 30); // 截取字符串
                $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').text(farmOrginfo);
                $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
                if (_vm.scorerIds.includes(',')) {
                    let newlist = _vm.scorerIds.split(',');
                    $('#scorer').val(newlist).trigger('change');
                } else {
                    $('#scorer').val(_vm.scorerIds).trigger('change');
                }
                let scorerinfo = cutstr(_vm.scorer, 30); // 截取字符串
                $('#scorer').next('.select2-container').find('.select2-selection__rendered').text(scorerinfo);
                $('#scorer').next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
            }

            _initEntry();
        }

        // 获取下一个分录的序号
        if (Utils.IsNotNull(getUrlKey('nextEntryId'))) {
            nextEntryId = getUrlKey('nextEntryId');
        }
        // 新增审查项
        $('#add-saleEntry').on('click', function () {
            // 存储主表数据
            let datas = {
                category: 2, // 千点评分审查
                farmOrg: {
                    id: _vm.farmOrg?.id || '',
                    name: _vm.farmOrg?.name || '',
                },
                type: _vm.type,
                bizDate: _vm.bizDate,
                adress: _vm.adress,
                adressName: _vm.adressName,
                scoreDate: _vm.scoreDate,
                scorer: _vm.scorer,
                scorerIds: _vm.scorerIds,
                remark: _vm.remark,
                leaders: _vm.leaders,
                leaderIds: _vm.leaderIds,
            };
            JSON.stringify(Utils.SetSessionStorage('getMainMessage', datas));

            if (Utils.IsNotNull(getUrlKey('id') || getUrlKey('mainId'))) {
                location.href = `../biosafety/addthouauditmainentry.html?v=${Utils.GetTime()}&id=${getUrlKey('id') || getUrlKey('mainId')}`;
            } else {
                location.href = `../biosafety/addthouauditmainentry.html?v=${Utils.GetTime()}`;
            }
        });
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            location.href = `../biosafety/auditmain.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                bottom: '-6rem',
                transition: 'all .ls ease-in',
            });
        });

        // 选择审查项
        $(document).on('click', '#add-salePlan', function () {
            if (!Utils.IsNotNull($('#type').val())) {
                return $.toptip(`请先选择审查类型!`, 'warning');
            }

            $('#pop').css('display', 'block');
            $('.show-box').css('display', 'block');
            $('.show-box').css({
                bottom: '0',
                transition: 'all .ls ease-in',
            });
            $('#saleplans-list').empty();

            _querySalePlansList(); //查询销售计划列表
        });

        // 审查项列表 确定
        $('#saleplansSubmit').on('click', function () {
            let salePlans = [];
            let checkSale = $('#saleplans-list').find($('input[type=checkbox]:checked'));
            let saleList = $('#salesEntry').find('.report-contents-item-box');
            for (var i = 0; i < checkSale.length; i++) {
                let res = checkSale[i].parentNode.dataset;
                let item = {
                    isHave: true,
                    seq: i + 1,
                    auditItemId: res.id,
                    text: res.text,
                    weight: res.weight,
                    isQualified: false,
                    isRectify: null,
                    deduct: '',
                    reason: '',
                    suggestion: '',
                    principal: '',
                    principalIds: '',
                    timeLimit: '',
                    result: '',
                    image: '',
                    score: '',
                    remark: '',
                };
                salePlans.push(item);
                getEntryInfo.push(item);
                nextEntryId++;
            }
            $('#salesEntry').append(addsaleTemplate(salePlans));
            JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));

            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                bottom: '-6rem',
                transition: 'all .ls ease-in',
            });
            _initEntry();
        });
    };

    // 删除分录
    const _delSalesEntry = () => {
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            operaEntry = $(this).parents('.report-contents-item-box').attr('id');
            deltips(operaEntry);
        });
    };
    // 删除分录提示
    const deltips = (operaEntry) => {
        $.modal({
            autoClose: false,
            title: '删除提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '确定',
                    onClick: function () {
                        let index = getEntryInfo.findIndex((s) => s.seq == operaEntry);
                        getEntryInfo.splice(index, 1);
                        JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));
                        _initEntry();
                        $.closeModal();
                    },
                },
            ],
        });
    };

    // 编辑分录
    const _ediSalesEntry = () => {
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储主表数据
            let datas = {
                category: 2, // 千点评分审查
                farmOrg: {
                    id: _vm.farmOrg?.id || '',
                    name: _vm.farmOrg?.name || '',
                },
                type: _vm.type,
                bizDate: _vm.bizDate,
                adress: _vm.adress,
                adressName: _vm.adressName,
                scoreDate: _vm.scoreDate,
                scorer: _vm.scorer,
                scorerIds: _vm.scorerIds,
                remark: _vm.remark,
                leaders: _vm.leaders,
                leaderIds: _vm.leaderIds,
            };
            JSON.stringify(Utils.SetSessionStorage('getMainMessage', datas));

            operaEntryId = $(this).parents('.report-contents-item-box').attr('id');
            if (Utils.IsNotNull(getUrlKey('id') || getUrlKey('mainId'))) {
                location.href = `../biosafety/addthouauditmainentry.html?v=${Utils.GetTime()}&operaEntryId=${operaEntryId}&id=${getUrlKey('id') || getUrlKey('mainId')}`;
            } else {
                location.href = `../biosafety/addthouauditmainentry.html?v=${Utils.GetTime()}&operaEntryId=${operaEntryId}`;
            }
        });
    };

    // 编辑和删除分录后，重新渲染分录
    const _initEntry = () => {
        // 获取分录数据
        getEntryInfo = JSON.parse(Utils.GetSessionStorage('getEntryInfo')) || [];
        // 分录数据赋值
        if (getEntryInfo) {
            getEntryInfo.forEach(function (item, index) {
                item.seq = index + 1;
            });
            JSON.stringify(Utils.SetSessionStorage('getEntryInfo', getEntryInfo));
            getEntryInfo.forEach((s) => {
                s.score = Utils.IsNotNull(s.deduct) ? Number(s.weight || 0) - Number(s.deduct || 0) : '';
            });
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));
        }
    };

    //TODO : 附件信息回显
    const _images = async (file) => {
        let _imag = file.split(',');
        if (_imag) {
            if (!uploader) {
                await uploadInit();
            }
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                await requestFilePath(_imag[i]).then((_res) => {
                    let _list = _vm.images;
                    _list.push({
                        id: _sun,
                        url: _res.data,
                        imageId: _imag[i],
                    });
                    if (_res.isSucceed) {
                        let _li;
                        if (['jpg', 'jpeg', 'png', 'gif'].indexOf(_imag[i].suffix) < 0) {
                            _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        } else {
                            _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                        }
                        $('#uploaderFiles').append(_li);
                    }
                });
            }
            if (_sun == 3) {
                $('.weui-uploader__input-box').hide();
            }
            _vm.uploadCount = _sun;
        }
    };

    // 保存
    const savedata = () => {
        if (!Utils.IsNotNull($(`#type`).select2('data'))) {
            return $.toptip(`请选择审查类型!`, 'warning');
        }
        if (!Utils.IsNotNull($(`#adress`).select2('data'))) {
            return $.toptip(`请选择审查地点!`, 'warning');
        }
        if (!Utils.IsNotNull(_vm.scorerIds)) {
            return $.toptip(`请选择审查人!`, 'warning');
        }
        if (!Utils.IsNotNull($(`#businessTime`).val())) {
            return $.toptip(`请选择业务日期!`, 'warning');
        }
        if (!Utils.IsNotNull($(`#scoreDate`).val())) {
            return $.toptip(`请选择审查日期!`, 'warning');
        }
        if (!Utils.IsNotNull(getEntryInfo)) {
            return $.toptip(`请添加分录信息!`, 'warning');
        }
        if (getEntryInfo.some((s) => s.isHave)) {
            return $.toptip(`请完善分录信息!`, 'warning');
        }
        let newList = getEntryInfo.map((s) => s.auditItemId);
        const uniqueArray = [...new Set(newList)];
        if (newList.length != uniqueArray.length) {
            return $.toptip(`分录信息存在重复项!`, 'warning');
        }
        getEntryInfo.forEach((s) => {
            s.category = 2; // 千点评分审查
            s.type = _vm.type;
        });
        savetips();
    };
    // 保存提示
    const savetips = () => {
        if (Utils.IsNotNull(getUrlKey('id') || getUrlKey('mainId'))) {
            savetype = '修改';
            addstyleEntry = 'display:none';
            edistyleEntry = 'display:block';
        } else {
            savetype = '保存';
            addstyleEntry = 'display:block';
            edistyleEntry = 'display:none';
        }
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" style="${addstyleEntry}" >是否确认${savetype}该单据？</div>
                        <div class="edientry" style="${edistyleEntry}">是否确认${savetype}并保存该单据？</div>
                    </div> 
                    </div>`,
            buttons: [
                {
                    text: '取消',
                    className: 'default',
                    onClick: function () {
                        $.closeModal();
                    },
                },
                {
                    text: '保存',
                    onClick: function () {
                        $.closeModal();
                        const propertiesToCopy = ['category', 'farmOrg', 'type', 'bizDate', 'adress', 'adressName', 'scoreDate', 'scorer', 'scorerIds', 'remark', 'leaders', 'leaderIds'];
                        let _param = propertiesToCopy.reduce((obj, prop) => {
                            obj[prop] = _vm[prop];
                            return obj;
                        }, {});
                        _param.entires = getEntryInfo;
                        if (Utils.IsNotNull(getUrlKey('id') || getUrlKey('mainId'))) {
                            AuditmainAPI.updateAuditTables(getUrlKey('id') || getUrlKey('mainId'), _param).then(
                                (res) => {
                                    $.toptip('千点评分审查修改成功', 'success');
                                    setTimeout(function () {
                                        location.href = `./auditmain.html`;
                                    }, 1000);
                                },
                                (err) => {
                                    $.toptip(err.responseJSON?.msg, 'error');
                                },
                            );
                        } else {
                            AuditmainAPI.setAuditTables(_param).then(
                                (res) => {
                                    $.toptip('千点评分审查创建成功', 'success');
                                    setTimeout(function () {
                                        location.href = `./auditmain.html`;
                                    }, 1000);
                                },
                                (err) => {
                                    $.toptip(err.responseJSON?.msg, 'error');
                                },
                            );
                        }
                    },
                },
            ],
        });
    };

    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat('...');
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串；
        if (str_length < len) {
            return str;
        }
    };
    // 获取地址栏的 参数
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    const selfAdaption = () => {
        document.addEventListener('touchstart', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        });

        document.addEventListener('touchmove', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        });
        document.addEventListener('touchend', function (event) {
            if (event.touches.length >= 2) {
                event.preventDefault();
            }
        });
    };
    // 控制返回按钮，返回的页面
    const ctlReturn = () => {
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
                //跳转列表
                this.window.location = `../biosafety/auditmain.html?v=${Utils.GetTime()} `;
            });
        }
    };

    //TODO : 附件上传
    const uploadInit = () => {
        weui.uploader('#uploader', {
            url: '',
            auto: false,
            type: 'file',
            compress: { isNoTCompress: true },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (['image/jpg', 'image/jpeg', 'image/png'].indexOf(this.type) < 0) {
                    $.toptip('请上传图片', 'warning');
                    return false; // 阻止文件添加
                }
                if (this.size > 8 * 1024 * 1024) {
                    $.toptip('请上传不超过8M的文件', 'warning');
                    return false;
                }
                $.showLoading('上传中..');
                _vm.uploadCount = ++_vm.uploadCount;
                if (_vm.uploadCount == 3) {
                    $('.weui-uploader__input-box').hide();
                }
            },
            onQueued: function () {
                let formFile = new FormData();
                let upFiles = this;
                let file = publicFileDraw(this.name, _vm);
                $.showLoading('上传中...');
                let fileName = sliceFileName(upFiles);
                let newfile = publicFileDraw(fileName, _vm);
                if (newfile != false && newfile != undefined) {
                    formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                    _uploadFileDraw(formFile, upFiles, _vm, newfile);
                }

                // if (file != false && file != undefined) {
                //     formFile.append('apiobjfile', new window.File([this], file, { type: this.type }));
                //     _uploadFileDraw(formFile, upFiles, _vm, file);
                // }
                // //确认提交
                // $('.weui-dialog__btn').on('click', function () {
                //     if ($(this)[0].innerHTML == '确认') {
                //         $.showLoading('上传中...');
                //         let fileName = sliceFileName(upFiles);
                //         let newfile = publicFileDraw(fileName, _vm);
                //         if (newfile != false && newfile != undefined) {
                //             formFile.append('apiobjfile', new window.File([upFiles], newfile, { type: upFiles.type }));
                //             _uploadFileDraw(formFile, upFiles, _vm, newfile);
                //         }
                //     }
                // });
                return true;
            },
        });
        $('#uploaderFiles').click(function (e) {
            let target = e.target;
            while (!target.classList.contains('weui-uploader__file') && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
                onDelete: function () {
                    //删除图片的回调
                    $.confirm({
                        title: '删除提示',
                        text: '确定删除该图片？',
                        onOK: function () {
                            let _id = $(target).attr('data-id');
                            _vm.images = _vm.images.filter((item) => item.id != _id);
                            _vm.uploadCount = --_vm.uploadCount;
                            target.remove();
                            gallery.hide();
                            // 添加3张后隐藏上传按钮
                            if (_vm.uploadCount == 3) {
                                $('.weui-uploader__input-box').hide();
                            } else {
                                $('.weui-uploader__input-box').show();
                            }
                        },
                        onCancel: function () {},
                    });
                },
            });
        });
    };

    /**
     *@file 附件上传
     *
     */
    const _uploadFileDraw = (formFile, upFiles, _vm, newName) => {
        uploadFile(formFile)
            .then((res) => {
                if (res.isSucceed) {
                    let _list = _vm.images;
                    _list.push({
                        id: $('#uploaderFiles li').length,
                        imageId: res.data,
                        url: upFiles.url,
                        name: newName,
                    });
                    _vm.attaches.push(res.data);
                    $('#uploaderFiles li').each(function (i) {
                        $(this).attr('data-id', _vm.images[i].id);
                        $(this).attr('data-image-id', _vm.images[i].imageId);
                        $(this).attr('data-name', _vm.images[i].name);
                        $(this).attr('data-suffix', _vm.images[i].type);
                        $(this).attr('data-url', _vm.images[i].url);
                        $(this).css({ 'background-image': `url(${_vm.images[i].url})` });
                    });
                    $('.weui-uploader__file-content').hide();
                    $('.weui-uploader__file').removeClass('weui-uploader__file_status');
                    $.hideLoading();
                    $.closeModal();
                }
            })
            .catch((res) => {
                $('#uploaderFiles li')
                    .eq($('#uploaderFiles li').length - 1)
                    .remove();
                _vm.uploadCount = --_vm.uploadCount;
                $.toptip(res.msg, 'error');
            })
            .finally((_) => {
                $.hideLoading();
                $.closeModal();
            });
    };

    // 获取审查项列表
    const _querySalePlansList = () => {
        AuditmainAPI.getAuditItemsList({ type: $('#type').val() }).then((res) => {
            // 审查类别 category:1生物安全审查；category:2千点评分审查
            let newList = res.filter((s) => s.category == 2);
            newList.map((item) => {
                let labhtml = `
                 <label class="weui-cell weui-cell_active weui-check__label" for="${item.id}" data-id="${item.id}" id="lab_${item.id}"
                    data-text="${item.text}" data-weight="${item.weight}">
					<input type="checkbox" class="" name="checkbox1" id="${item.id}" style="width: 25px;height: 25px;">
					<div class="" aria-hidden="true" style='margin-left: 15px;'>
						<span style="color:#4d4d4d">审查内容：</span><span class="lab_name" style="color:#4d4d4d">${item.text}</span>
                         <div class="demo_badge_desc lab_numCode" style="color:#4d4d4d">
                          权重分：<span>${item.weight}</span>&nbsp;
                        </div>
					</div>
				</label>`;
                $('#saleplans-list').append(labhtml);
            });
            $('#saleplans-list').append(`<div class="weui-loadmore weui-loadmore_line"><span class="weui-loadmore__tips">已经到底了</span></div>`);
            $('#saleplans-list').append(`<div style="height:110px"></div>`);
        });
    };

    //TODO :初始化下拉框内容
    const initSelectValue = async () => {
        // 选择日期
        $('#search-date').on('click', function () {
            pickIsolationDate();
        });
        // 选择日期
        $('#scoreDate-date').on('click', function () {
            pickDepartureDate();
        });
        // 审查类型
        await requestDict(DictionaryType.AUDIT_TYPE).then((res) => {
            typeInfo = _.cloneDeep(res.data);
            $('#type')
                .empty()
                .select2({
                    placeholder: '请选择审查类型...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: res.data.map((item) => {
                        return {
                            id: item.value,
                            text: item.displayName,
                        };
                    }),
                });
            $('#type').setSelectValue();
        });
        // 选择审查类型
        $('#type')
            .on('select2:select', function () {
                _vm.type = $(this).select2('data')[0]?.id;
                AuditmainAPI.getAuditItemsList({ type: $('#type').val() }).then((res) => {
                    // 生物安全审查 category:1
                    let newList = res.filter((s) => s.category == 2);
                    let salePlans = [];
                    for (var i = 0; i < newList.length; i++) {
                        let res = newList[i];
                        let item = {
                            seq: i + 1,
                            auditItemId: res.id,
                            text: res.text,
                            weight: res.weight,
                            isQualified: false,
                            isRectify: null,
                            deduct: '',
                            reason: '',
                            suggestion: '',
                            principal: '',
                            principalIds: '',
                            timeLimit: '',
                            result: '',
                            image: '',
                            score: '',
                            remark: '',
                        };
                        salePlans.push(item);
                    }
                    $('#salesEntry').empty().append(addsaleTemplate(salePlans));
                    JSON.stringify(Utils.SetSessionStorage('getEntryInfo', salePlans));
                    _initEntry();
                });
            })
            .on('select2:clear', function () {
                $('#salesEntry').empty();
            });

        // 审查地点
        await requestDict(DictionaryType.AUDITADDRESS_TYPE).then((res) => {
            placeInfo = _.cloneDeep(res.data);
            $('#adress')
                .empty()
                .select2({
                    placeholder: '请选择审查地点...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: res.data.map((item) => {
                        return {
                            id: item.value,
                            text: item.displayName,
                        };
                    }),
                });
            $('#adress').setSelectValue();
        });
        // 获取所有猪厂
        await AuditmainAPI.getSubdata('LIVESTOCK-FARMS').then((res) => {
            farmOrgInfo = _.cloneDeep(JSON.parse(res));
            $('#farmOrg')
                .empty()
                .select2({
                    placeholder: '请选择猪厂...', //默认文字提示
                    language: 'zh-CN', //汉化
                    allowClear: true, //允许清空
                    data: farmOrgInfo.map((item) => {
                        return {
                            id: item.Id,
                            text: `${item.Name}`,
                            name: item.Name,
                        };
                    }),
                });
            $('#farmOrg').setSelectValue();
        });
        // 选择
        $('#adress')
            .on('select2:select', function () {
                _vm.adress = $(this).select2('data')[0]?.id;
                _vm.adressName = $(this).select2('data')[0]?.text;
                let data = $(this).select2('data')[0]?.text;
                let id = farmOrgInfo.find((s) => s.Name == data.replace('场', '厂'))?.Id || '';
                if (id) {
                    $('#farmOrg').val(id).trigger('change');
                    _vm.farmOrg.id = id;
                    _vm.farmOrg.name = data;
                    let saleOrgsinfo = cutstr(_vm.farmOrg.name, 30); // 截取字符串
                    $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
                    $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
                } else {
                    $('#farmOrg').setSelectValue();
                }
            })
            .on('select2:clear', function () {
                $('#farmOrg').setSelectValue();
            });

        // 选择
        $('#farmOrg').on('select2:select', function () {
            let data = $(this).select2('data')[0];
            _vm.farmOrg.id = $(this).val();
            _vm.farmOrg.name = data?.text;
            let saleOrgsinfo = cutstr(_vm.farmOrg.name, 30); // 截取字符串
            $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
            $('#farmOrg').next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
        });

        // 获取人员列表
        // await AuditmainAPI.getPersonList().then(res => {
        //     personList = res.items.map(item => {
        //         return { ...item, text: item.name }
        //     })
        //     $('#scorer,#leaders').empty().select2({
        //         placeholder: '请选择审查人...', //默认文字提示
        //         language: "zh-CN",//汉化
        //         allowClear: true,//允许清空
        //         data: personList,
        //     });
        //     $('#scorer,#leaders').setSelectValue();
        // })
        $(`#scorer,#leaders`)
            .empty()
            .select2({
                language: 'zh-CN',
                allowClear: true, //允许清空
                placeholder: '请选择员工...', //默认文字提示
                ajax: {
                    url: Utils.CurDomain.EmployeeMgtUrl + `/emplrecds/by/q`,
                    dataType: 'json',
                    type: 'GET',
                    beforeSend: Utils.AjaxBeforeSend,
                    data: function (params) {
                        return {
                            Status: true,
                            // SearchInfo: params.term,
                            PageSize: 20,
                            PageIndex: (params.page || 1) - 1,
                            ...(Utils.IsNotNull(params.term) ? { SearchInfo: params.term } : {}),
                        };
                    },
                    processResults: function (data, params) {
                        params.page = params.page || 1;
                        let _data = data.data.items.map((item) => {
                            item.text = `${item.name}(${item.numCode})`;
                            return item;
                        });
                        return {
                            results: _data, // 后台返回的数据集
                            pagination: {
                                more: params.page < data.data.totalPages, // 总页数为10，那么1-9页的时候都可以下拉刷新
                            },
                        };
                    },
                    minimumInputLength: 1,
                    cache: true,
                    delay: 700, //等待用户输入完后的 在等700毫秒 进行搜索
                    error: Utils.AjaxError,
                },
            });
        $('#scorer,#leaders').setSelectValue();
        // 选择
        $('#scorer').on('select2:select', function () {
            let list = $(this).select2('data');
            _vm.scorerIds = list
                .map((item) => {
                    return item.id;
                })
                .join(',');
            _vm.scorer = list
                .map((item) => {
                    return item.text;
                })
                .join(',');
            let saleOrgsinfo = cutstr(_vm.scorer, 30); // 截取字符串
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
            $(this).next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
        });
        // 选择
        $('#leaders').on('select2:select', function () {
            let list = $(this).select2('data');
            _vm.leaderIds = list
                .map((item) => {
                    return item.id;
                })
                .join(',');
            _vm.leaders = list
                .map((item) => {
                    return item.text;
                })
                .join(',');
            let saleOrgsinfo = cutstr(_vm.leaders, 30); // 截取字符串
            $(this).next('.select2-container').find('.select2-selection__rendered').text(saleOrgsinfo);
            $(this).next('.select2-container').find('.select2-selection__rendered').css({ 'text-align': 'left' });
        });
    };

    // 时间选择器
    const pickIsolationDate = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                // let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                let value = result.map((item) => item.value).join('-');
                _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD');
            },
        });
    };

    // 时间选择器
    const pickDepartureDate = () => {
        weui.datePicker({
            defaultValue: moment(new Date()).format('YYYY-MM-DD').split('-'),
            // end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                // let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                let value = result.map((item) => item.value).join('-');
                _vm.scoreDate = moment(new Date(value)).format('YYYY-MM-DD');
            },
        });
    };
})(window, document, jQuery);
